package cn.wolfcode.luowowo.website.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 表现层对cookie的操作
 */
public class CookieUtil {

    /**
     * 向浏览器中添加cookie
     *
     * @param key      cookie的名字
     * @param value    cookie的值
     * @param time     cookie的过期时间
     * @param response 响应对象
     */
    public static void addCookie(String key, String value, int time, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, value);
        // 设置 cookie的过期时间
        cookie.setMaxAge(time);
        // 设置 cookie的路径
        cookie.setPath("/");
        // 将 cookie响应到 浏览器中
        response.addCookie(cookie);
    }

    /**
     * 设置cookie的过期时间
     *
     * @param cookieName cookie的名字
     * @param time       过期时间 单位为秒
     * @param response   响应对象
     * @param request    请求对象
     */
    public static void extendCookie(String cookieName, int time, HttpServletResponse response, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return;
        }
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                cookie.setMaxAge(time);
                // 设置 cookie的路径
                cookie.setPath("/");
                // 将 cookie响应到 浏览器中
                response.addCookie(cookie);
                return;
            }
        }
    }

    /**
     * 通过cookie的名字获取cookie的值
     *
     * @param request                 请求对象
     * @param userInfoTokenCookieName cookie的名字
     * @return
     */
    public static String getToken(HttpServletRequest request, String userInfoTokenCookieName) {
        // 获取所有的cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (userInfoTokenCookieName.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 删除cookie
     *
     * @param request
     * @param userInfoTokenCookieName
     * @return
     */
    public static void deleteCookie(HttpServletRequest request, String userInfoTokenCookieName) {
        // 获取所有的cookie
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return;
        }
        for (Cookie cookie : cookies) {
            if (userInfoTokenCookieName.equals(cookie.getName())) {
                cookie.setMaxAge(0);
                return;
            }
        }
    }


}
